package com.glsc.ngateway.opmanage.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.glsc.ngateway.common.base.domain.mysql.gateway.other.SystemConfig;
import com.glsc.ngateway.common.base.repo.mysql.gateway.other.SystemConfigRepository;
import com.glsc.ngateway.common.api.common.enums.Constant;
import com.glsc.ngateway.common.api.common.ex.GatewayException;
import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.opmanage.utils.SpecificationUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: zhaoxc
 * @Date: 2020/6/23 18:00
 * @Desc: 配置表服务类
 */
@Service
public class SystemConfigService {

    private static Logger logger = LoggerFactory.getLogger(SystemConfigService.class);

    @Resource
    private SystemConfigRepository systemConfigRepository;

//    @Resource
//    private JdbcTemplate jdbcTemplate;

    /**
     * 保存实体
     * @param systemConfig
     * @return SystemConfig
     */
    public SystemConfig saveSystemConfig(SystemConfig systemConfig) {
        SystemConfig systemConfigDB = this.findByCode(systemConfig.getConfigCode());
        if (systemConfigDB != null && !systemConfigDB.getConfigId().equals(systemConfig.getConfigId())) {
            throw GatewayException.error("已有相同配置代码系统配置，不允许重新添加！");
        }
        return systemConfigRepository.save(systemConfig);
    }

    /**
     * 查找实体
     * @param id
     * @return SystemConfig
     */
    public SystemConfig findById(Integer id) {
        Optional<SystemConfig> optional = systemConfigRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        } else {
            return null;
        }
    }

    public void deleteById(Integer id) {
        systemConfigRepository.deleteById(id);
    }


    /**
     * 分页条件查询
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<SystemConfig> findPage(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "configId";

        pageNo= PageUtil.initPageNo(pageNo);
        pageSize=PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        return systemConfigRepository.findAll(SpecificationUtil.buildSpecification(param, SystemConfig.class), pageable);
    }

    /**
     * 根据条件查询List
     */
    public List<SystemConfig> findList(Map<String, Object> param) {
        if (null == param || param.size() == 0) {
            return systemConfigRepository.findAll();
        } else {
            return systemConfigRepository.findAll(SpecificationUtil.buildSpecification(param, SystemConfig.class));
        }
    }

    /**
     * 根据code更新系统配置值
     * @param configCode
     * @param configValue
     * @return SystemConfig
     */
    public void updateConfigValueByCode(String configCode,String configValue) {
        SystemConfig systemConfig = findByCode(configCode);
        if(systemConfig != null){
            systemConfig.setConfigValue(configValue);
            systemConfigRepository.save(systemConfig);
        }
    }

    /**
     * 根据code查询systemConfig
     */
    public SystemConfig findByCode(String configCode) {
        SystemConfig config = new SystemConfig();
        config.setConfigCode(configCode);
        Example<SystemConfig> example = Example.of(config);
        Optional<SystemConfig> optional = systemConfigRepository.findOne(example);

        if (optional.isPresent()) {
            return optional.get();
        } else {
            return null;
        }
    }

    /**
     * 根据code查询systemConfig
     */
    public String findConfigValueByCode(String configCode) {
        SystemConfig config = this.findByCode(configCode);
        if (null == config || StrUtil.isEmpty(config.getConfigValue())) {
            return "";
        } else {
            return StrUtil.trim(config.getConfigValue());
        }
    }

    /**
     * 根据code查询systemConfig的整数
     */
    public Integer findIntValueByCode(String configCode) {
        String configStr = this.findConfigValueByCode(configCode);
        Integer configInt = null;
        try {
            if (StrUtil.isNotEmpty(configStr)) {
                configInt = Integer.parseInt(configStr);
            }
        } catch (Exception e) {

        }
        return configInt;
    }

    /**
     * 根据code查询systemConfig
     */
    public Integer findConfigValueIntByCode(String configCode) {
        String intStr = this.findConfigValueByCode(configCode);
        Integer resultInt = null;

        try {
            resultInt = Integer.parseInt(StrUtil.trim(intStr));
        } catch (Exception e) {
            resultInt = null;
        }
        return resultInt;
    }

    /**
     * 根据code查询systemConfig，配置为逗号分割的多个字符串
     */
    public List<String> findConfigValueAsListByCode(String configCode) {
        return findConfigValueAsListByCode(configCode, ",");
    }

    /**
     * 根据code查询systemConfig，配置为指定分隔符分割的多个字符串
     *
     * @param splitChar 配置项的分隔符，如果未空，则标识不分割
     */
    public List<String> findConfigValueAsListByCode(String configCode, String splitChar) {
        SystemConfig config = this.findByCode(configCode);

        List<String> resultList = new ArrayList<>();
        if (null == config) {
            return resultList;
        }

        //判空处理
        String configValue = config.getConfigValue();
        if (StrUtil.isEmpty(configValue) || StrUtil.isEmpty(configValue.trim())) {
            return resultList;
        }

        //逗号分割字符串分割
        if (StrUtil.isEmpty(splitChar)) {
            resultList.add(configValue);
        } else {
            splitChar = splitChar.trim();
            resultList = Arrays.stream(configValue.split(splitChar)).collect(Collectors.toList());

        }
        return resultList;
    }

    /**
     * 根据code列表查询systemConfig，配置为逗号分割的多个字符串
     */
    public List<String> findConfigValueAsListByCodeList(List<String> configCodeList) {
        return findConfigValueAsListByCodeList(configCodeList, ",");
    }

    /**
     * 根据code列表查询systemConfig，配置为指定分隔符分割的多个字符串
     *
     * @param splitChar 配置项的分隔符，如果未空，则标识不分割
     */
    public List<String> findConfigValueAsListByCodeList(List<String> configCodeList, String splitChar) {
        List<SystemConfig> configList = systemConfigRepository.findByConfigCodeIn(configCodeList);

        List<String> resultList = new ArrayList<>();
        if (CollectionUtil.isEmpty(configList)) {
            return resultList;
        }
        boolean needSplit = StrUtil.isNotBlank(splitChar);
        if (needSplit) {
            splitChar = splitChar.trim();
        }
        //遍历处理
        for (SystemConfig config : configList) {
            //判空处理
            String configValue = config.getConfigValue();
            if (StrUtil.isBlank(configValue)) {
                continue;
            }

            //逗号分割字符串分割
            if (needSplit) {
                List<String> valueList = Arrays.stream(configValue.split(splitChar)).collect(Collectors.toList());
                resultList.addAll(valueList);
            } else {
                resultList.add(configValue);
            }
        }
        return resultList;
    }

    /**
     * 获取数据库当前时间
     */
//    public java.sql.Timestamp getSysdate(){
//        java.sql.Timestamp now=systemConfigRepository.getSysdate();
//        if(now==null){
//            throw GatewayException.error("获取系统时间失败");
//        }
//        return now;
//    }

//    /**
//     * 获取特定日期以后200个交易日
//     */
//    public List<TradeCalendarDto> findTradeDaysAfter(String beginDate,Integer dayCount) {
//        if (StrUtil.isEmpty(beginDate) || dayCount == null || dayCount <= 0) {
//            throw GatewayException.error("查询交易日参数为空，非法，开始日期=" + beginDate + "，取天数=" + dayCount);
//        }
//        String sql = "select DATE_FORMAT(trade_days,'%Y-%m-%d') as tradeDate,exchange,ROW_NUMBER () over(order by vc_trade_dt) as sortNo from t_glam_trade_calendar where exchange ='SSE' and vc_trade_dt>=" + beginDate + " order by  vc_trade_dt limit 0,"+dayCount;
//        List<Map<String, Object>> results = jdbcTemplate.queryForList(sql);
//        List<TradeCalendarDto> ret = new ArrayList<>();
//
//        if (!CollectionUtils.isEmpty(results)) {
//            results.forEach(item -> {
//                TradeCalendarDto dto = new TradeCalendarDto();
//                dto.setTradeDate(item.get("tradeDate").toString());
//                dto.setExchange(item.get("exchange").toString());
//                dto.setSortNo(Integer.parseInt(item.get("sortNo").toString()));
//                ret.add(dto);
//            });
//        }
//
//        return ret;
//    }

    /**
     * 查询文件上传根目录
     */
    public String getFileUploadRoot() {
        String uploadRoot = this.findConfigValueByCode(Constant.CONFIG_KEY_UPLOAD_ROOT);
        logger.info("文件上传根目录：uploadRoot=" + uploadRoot);
        if (StrUtil.isNotEmpty(uploadRoot)) {
            uploadRoot = StrUtil.trim(uploadRoot);
            if (!uploadRoot.endsWith("/")) {
                uploadRoot = uploadRoot + File.separator;
            }
        }

        if (StrUtil.isEmpty(uploadRoot)) {
            uploadRoot = "/";
        }

        logger.info("文件上传根目录" + uploadRoot);
        return uploadRoot;
    }

}
